#!/usr/bin/env python
"""
urlcheck.py will spawn this script for every
domain that doesn't work.

"""
import urllib2
import time
import optparse
from mailer import mailer
from dbwork import DataBase


class Check:
    
    def __init__(self):
        self.db = DataBase()

    def errors(self, website):
    	""" 
    	Tries to connect to the website
    	and returns True if it finds issues
    	"""
    	try:
    		urllib2.urlopen(website)
    	except urllib2.HTTPError, e:
    		return True

    	except urllib2.URLError, e:
    		return True


    def delayed_check(self, website):
    	"""Runs all the time every 60 seconds (default)"""
    	time.sleep(60)
    	if errors(website) is True:
    		delayed_check(website)
    	else:
    		text_body = "The following website is now running properly: %s" % website
    		subj = "%s is OK" % website
    		self.db.delete(website)
    		notify(text_body, subj)

def notify(text_body, subj):
	""" Sends an email with information """
	user = ""
	passwd = ""
	to = [""]
	subject = subj
	text = text_body
	mailer(user, passwd, to, subject, text)

def main():
	p = optparse.OptionParser()
	options, args = p.parse_args()
	
	if len(args) == 1:
		website = args[0]
		delayed_check(website)
	else:
		p.print_help()

if __name__ == '__main__':
	main()
		

